package com.thememaker.lockstyle.control;

import com.alibaba.fastjson.JSON;
import com.thememaker.lockstyle.LockstyleMainController;
import com.thememaker.lockstyle.LockstyleShowUtils;
import com.thememaker.lockstyle.bean.Var;
import com.thememaker.lockstyle.bean.command.BaseCommand;
import com.thememaker.lockstyle.bean.command.Trigger;
import com.thememaker.lockstyle.bean.command.Triggers;
import com.thememaker.lockstyle.bean.command.VariableCommand;
import com.thememaker.lockstyle.bean.ui.BaseView;
import com.thememaker.lockstyle.bean.ui.Group;
import com.thememaker.lockstyle.bean.ui.Image;
import com.thememaker.lockstyle.bean.ui.Wallpaper;
import com.thememaker.lockstyle.parsii.ExpressionUtils;
import com.thememaker.lockstyle.parsii.LockscreenViewPaesiiUtils;
import com.thememaker.util.SVGLoadUtils;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Optional;
import java.util.function.Consumer;


public class WallpaperControl implements ILockscreenControl {

    private   LockscreenViewPaesiiUtils lockscreenViewPaesiiUtils = new LockscreenViewPaesiiUtils();
    private VBox vBox;
    private LockstyleShowUtils lockstyleShowUtils ;

    public void setLockstyleShowUtils(LockstyleShowUtils lockstyleShowUtils) {
        this.lockstyleShowUtils = lockstyleShowUtils;
    }

    public WallpaperControl() {
    }

//    private WallpaperControl(Document document, ThemeFileInfo themeFileInfo) {
//        this.document = document;
//        this.themeFileInfo = themeFileInfo;
//    }

    @Override
    public Node initLockscreenControl(BaseView baseView, Path lockscreenPath,ExpressionUtils expressionUtils,Consumer<BaseView> consumer) {
        vBox = LayoutComponentUtils.getInstance().getControlView(670,600);
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlTitleLabel("锁屏壁纸"));
        Optional<String> optional1  = Optional.ofNullable(baseView).filter(baseView1 -> baseView1 instanceof Image)
                .map(baseView1 ->  LockscreenViewPaesiiUtils.getInstance(expressionUtils).paesiiImagePath((Image)baseView1,lockscreenPath.toString()).toString());
        Optional<String> optional2 = Optional.ofNullable(baseView).filter(baseView1 -> baseView1 instanceof Wallpaper)
                .map(baseView1 -> LockscreenViewPaesiiUtils.getInstance(expressionUtils)
                        .paesiiWallpaperPath((Wallpaper) baseView1, lockscreenPath.toString(), expressionUtils.getScreen_height()).toString());
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getWallpaperPane(lockscreenPath,optional1.orElse(optional2.orElse(null)),1080,2400,path -> {
            consumer.accept(Optional.ofNullable(baseView).orElse(getWallpaperView()));
        }));
//        HBox hBox = new HBox();
//        Button saveBtn = new Button("保存");
//        saveBtn.setId("diy-button");
//        saveBtn.setGraphic(SVGLoadUtils.getInstance().getSaveSVG(12, LockstyleMainController.buttonColor));
//        saveBtn.setOnAction(e->{
//            saveBgs();
//        });
//
//        Button addBtn = new Button("添加");
//        addBtn.setId("diy-button");
//        addBtn.setOnAction(event->{
//            addBGs();
//        });
//        Button deleBtn = new Button("删除");
//        deleBtn.setId("diy-button");
//        deleBtn.setOnAction(event->{
//            deleBGs(0);
//        });

//        if (baseView !=null){
//            if (baseView instanceof Image){
//                vBox.getChildren().add(LayoutComponentUtils.getInstance().getWallpaperPane(lockscreenPath,
//                        LockscreenViewPaesiiUtils.getInstance(expressionUtils).paesiiImagePath((Image)baseView,lockscreenPath.toString()).toString(),1080,2400,path -> {
//                            consumer.accept(baseView);
//                        }));
//            }else if (baseView instanceof Wallpaper){
//                vBox.getChildren().add(LayoutComponentUtils.getInstance().getWallpaperPane(lockscreenPath,
//                        LockscreenViewPaesiiUtils.getInstance(expressionUtils).paesiiWallpaperPath(
//                                (Wallpaper) baseView,lockscreenPath.toString(),expressionUtils.getScreen_height()).toString(),1080,2400,path -> {
//                            consumer.accept(baseView);
//                        }));
//            }
//        }else{
//            vBox.getChildren().add(LayoutComponentUtils.getInstance().getWallpaperPane(lockscreenPath,null,1080,2400,path -> {
//
//                        consumer.accept(baseView);
//                    }));
//        }
//        hBox.getChildren().addAll(saveBtn,addBtn,deleBtn);
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlNormalLabel("图片格式：JPG"));
        vBox.getChildren().add(LayoutComponentUtils.getInstance().getControlNormalLabel("图片尺寸：1080*2400"));
//        vBox.getChildren().add(hBox);
        return vBox;
    }

    private BaseView getWallpaperView(){
        Image image = new Image();
        image.setName("bg");
        image.setSrc("default_lock_wallpaper2400.jpg");
        image.setX("0");
        image.setY("0");
        return image;
    }

    @Override
    public Node getCacheLockscreenControl() {
        return vBox;
    }

    @Override
    public void updateView() {

    }


    private Group addBgImage(int num){
        Group group = new Group();
        group.setName("bg_btn_grp");
        group.setX("0");
        group.setY("0");
        group.setH("#screen_height");
        group.setW("#screen_width");
        com.thememaker.lockstyle.bean.ui.Button bgBtn = new com.thememaker.lockstyle.bean.ui.Button();
        bgBtn.setX("0");
        bgBtn.setY("0");
        bgBtn.setW("#screen_width");
        bgBtn.setH("#screen_height");
        bgBtn.setName("bg_btn");
        Triggers triggers = new Triggers();
        Trigger trigger = new Trigger();
        trigger.setAction("double");
        VariableCommand variableCommand = new VariableCommand();
        variableCommand.setConstString("true");
        variableCommand.setPersist("true");
        variableCommand.setExpression("ifelse(ge(#bgId,"+num+"),1,#bgId+1)");
        variableCommand.setName("bgId");
        System.out.println("----------"+variableCommand);
//        trigger.getCommandMap().put("ceshi",variableCommand);
        LinkedHashMap<String,BaseCommand> bas = new LinkedHashMap<>();
        bas.put("bg_variableCommand",variableCommand);
        trigger.setCommandMap(bas);
        LinkedHashMap<String,Trigger> triggerHashMap = new LinkedHashMap<>();
        triggerHashMap.put("bg_trigger",trigger);
        triggers.setTriggerMap(triggerHashMap);
        bgBtn.setTriggers(triggers);
        LinkedHashMap<String,BaseView> linkedHashMap = new LinkedHashMap<>();
//        linkedHashMap.put("var_bgId",bgId);
        linkedHashMap.put("bg_btn",bgBtn);
        group.setGroupViewMap(linkedHashMap);
        return group;
    }
//    private Image revisionBgImage(Image bg){
//        Path path = lockscreenViewPaesiiUtils.paesiiImagePath(bg,LayoutComponentUtils.lockscreenPath.toFile().toString());
//        String newName = StringUtils.substringBeforeLast(path.toString(),"\\")+"\\default_lock_wallpaper_2400_1.jpg";
//        File oldFile = new File(path.toString());
//        File newFile = new File(newName);
//        boolean flag = oldFile.renameTo(newFile);
//        if (flag) {
//            System.out.println("重命名成功");
//        } else {
//            System.out.println("重命名失败");
//        }
//        int exist = bg.getSrc().indexOf("/");
//        String src = "";
//        if(exist!=-1){
//
//            bg.setSrc("default_lock_wallpaper_2400_1.jpg");
//        }else {
//            src = StringUtils.substringBeforeLast(bg.getSrc(),"/");
//            bg.setSrc(src+"/default_lock_wallpaper_2400_1.jpg");
//        }
//        System.out.println("测试bg的src是否正确"+bg.getSrc());
//
//        return bg;
//    }

    private VBox rightVBox(Consumer<BaseView> consumer){
        BaseView baseView = new BaseView();
        Stage stage = new Stage();
        VBox rigthVBox = new VBox();
        rigthVBox.setMaxSize(300,600);
        rigthVBox.setMinSize(300,500);
        rigthVBox.setPrefSize(300,500);
        rigthVBox.setStyle("-fx-border-color: red;-fx-border-width: 2");
//        rigthVBox.setPadding(new Insets(20,20,20,20));
//        VBox.setMargin(rigthVBox,new Insets(20,20,20,20));
//        rigthVBox.setStyle("-fx-background-color: red");


        Button addBg = new Button("添加");
        Button deleBg = new Button("删除");
        HBox previewArea = new HBox();
        previewArea.setMinSize(216,480);

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setPrefSize(220,480);
        scrollPane.setMaxSize(220,480);
        previewArea.setStyle("-fx-border-color: red;-fx-border-width: 2");
        addBg.setOnAction(e->{
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("Open Resource File");
//            fileChooser.showOpenDialog(stage);
            File file = fileChooser.showOpenDialog(stage);
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("JPG", "*.jpg")
            );
            if(file!=null){
                LayoutComponentUtils.bgNum = LayoutComponentUtils.bgNum+1;
                LayoutComponentUtils.bgsPath.add(file.getPath());
            }


//            previewArea.getChildren().add(previewBg(LayoutComponentUtils.lockscreenPath,file.getPath().toString(),consumer,LayoutComponentUtils.bgNum));
        });
        scrollPane.setContent(previewArea);

        addBg.setId("diy-button");
        deleBg.setId("diy-button");

//        previewArea.getChildren().add();
        HBox btnHBox = new HBox();

        btnHBox.getChildren().add(addBg);
        btnHBox.getChildren().add(deleBg);

        rigthVBox.getChildren().add(LayoutComponentUtils.getInstance().getControlNormalLabel("请添加壁纸"));
        rigthVBox.getChildren().add(previewArea);
        rigthVBox.getChildren().add(btnHBox);
        return rigthVBox;
    }

    private void addBGs(){
        Stage stage = new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片");
        File file = fileChooser.showOpenDialog(stage);
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JPG", "*.jpg")
        );
        if(file!=null){
            LayoutComponentUtils.bgNum = LayoutComponentUtils.bgNum+1;
            LayoutComponentUtils.bgsPath.add(file.getPath());
        }
        System.out.println(LayoutComponentUtils.bgsPath.toString());
    }
    private void deleBGs(int id){
        if(id<LayoutComponentUtils.bgsPath.size()){
            LayoutComponentUtils.bgsPath.remove(id);
        }
        System.out.println(LayoutComponentUtils.bgsPath.toString());
    }
//    private void saveBgs(){
//    lockstyleShowUtils.getLockscreen();
//        if (lockstyleShowUtils.getLockscreen()!=null){
//            LinkedHashMap<String,BaseView> newBaseView = new LinkedHashMap<>();
//            LinkedHashMap<String,BaseView> baseViewLinkedHashMap = lockstyleShowUtils.getLockscreen().getLockScreenViewMap();
//            Image image = new Image();
//            image.setX("200");
//            image.setY("200");
//            image.setName("yuan_tong");
//            lockstyleShowUtils.getLockscreen().getLockScreenViewMap().put("image_new",image);
//            System.err.println("lockstyleShowUtils.getLockscreen().getLockScreenViewMap() >>> " + JSON.toJSONString(lockstyleShowUtils.getLockscreen().getLockScreenViewMap()));
//            Var bgId = new Var();
//            bgId.setConstString("true");
//            bgId.setExpression("1");
//            bgId.setPersist("true");
//            bgId.setName("bgId");
//            newBaseView.put("lockscreen_Var_0",bgId);
//            baseViewLinkedHashMap.keySet().forEach(e->{
//                BaseView baseView = baseViewLinkedHashMap.get(e);
////                System.out.println("------------------------"+e);
//                if(baseView instanceof Wallpaper){
//                   ((Wallpaper) baseView).setSrcid("#bgId");
//                   ((Wallpaper) baseView).getSrc();
//                   String  src = ((Wallpaper) baseView).getSrc();
//                   int exist = src.indexOf("/");
//                   if(exist==-1){
//                       src="default_lock_wallpaper_2400.jpg";
//                   }else {
//                       src = StringUtils.substringBeforeLast(src,"/")+"/default_lock_wallpaper_2400.jpg";
//                   }
//                   ((Wallpaper) baseView).setSrc(src);
//                }
//                newBaseView.put(e,baseView);
//            });
//
//            newBaseView.put("lockscreen_Group_50000",addBgImage(2));
//            System.out.println("这个值是假的------------");
//            lockstyleShowUtils.getLockscreen().setLockScreenViewMap(newBaseView);
////            lockstyleShowUtils.setLockscreen(lockscreen);
//            Group group = (Group) newBaseView.get("lockscreen_Group_50000");
//            System.out.println(group.getGroupViewMap());
//        }
////        LayoutComponentUtils.lockscreen = lockscreen;
//    }
}
